package com.jsnkj.basic.photo

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.jsnkj.basic.R
import com.jsnkj.basic.config.PuzzleConfig
import com.jsnkj.basic.databinding.ActivityPuzzlePhotoBinding
import com.jsnkj.basic.mvvm.BaseMVVMActivity
import com.jsnkj.basic.mvvm.HttpViewModel


/**
 * @功能描述: 拼图 相册界面
 * @创建时间: 2021/12/30
 * @创建者: 阳
 * @修改时间: 2021/12/30
 * @修改者: 阳
 */
class PuzzlePhotoActivity :
    BaseMVVMActivity<ActivityPuzzlePhotoBinding, HttpViewModel>() {
    override val layoutId: Int
        get() = R.layout.activity_puzzle_photo

    private lateinit var photoFragment: PuzzlePhotoFragment

    private var photoSize = -1

    private var limitMin = -1 //图片选取最小参数
    private var limitMax = -1 //图片选取最大参数

    companion object {
        fun startActivity(activity: Activity, photoSize: Int, requestCode: Int) {
            val intent = Intent(activity, PuzzlePhotoActivity::class.java)
            intent.putExtra("photoSize", photoSize)
            activity.startActivityForResult(intent, requestCode)
        }

        fun startActivity(activity: Activity, limitMin: Int, limitMax: Int, requestCode: Int) {
            if (limitMax <= limitMin) {
                Toast.makeText(activity, "数量返回设置异常，请重新设置", Toast.LENGTH_SHORT).show()
            }
            val intent = Intent(activity, PuzzlePhotoActivity::class.java)
            intent.putExtra("limitMin", limitMin)
            intent.putExtra("limitMax", limitMax)
            activity.startActivityForResult(intent, requestCode)
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        photoSize = intent.getIntExtra("photoSize", -1)
        limitMax = intent.getIntExtra("limitMax", -1)
        limitMin = intent.getIntExtra("limitMin", -1)

        findViewById<TextView>(R.id.txt_top_title).text = "相册"
        findViewById<ImageView>(R.id.image_return).setOnClickListener {
            onBackPressed()
        }

        val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)

        if (null != fragment && fragment is PuzzlePhotoFragment) {
            photoFragment = fragment
            photoFragment.photoSize = photoSize
            photoFragment.limitMin = limitMin
            photoFragment.limitMax = limitMax

            photoFragment.setOnSelectPhotoListener { photoList ->
                // 选中照片回调
                val intent = Intent()
                intent.putStringArrayListExtra(PuzzleConfig.ALBUM_RESULT, photoList)
                setResult(RESULT_OK, intent)
                onBackPressed()
            }
        }
    }

    override fun onStart() {
        super.onStart()

        if (this::photoFragment.isInitialized) {
            photoFragment.loadPhoto()
        }
    }

}